package com.yun.baymax.activity;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;

import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.app.TakePhotoImpl;
import com.jph.takephoto.compress.CompressConfig;
import com.jph.takephoto.compress.CompressImage;
import com.jph.takephoto.compress.CompressImageImpl;
import com.jph.takephoto.model.InvokeParam;
import com.jph.takephoto.model.TContextWrap;
import com.jph.takephoto.model.TImage;
import com.jph.takephoto.model.TResult;
import com.jph.takephoto.permission.InvokeListener;
import com.jph.takephoto.permission.PermissionManager;
import com.jph.takephoto.permission.TakePhotoInvocationHandler;
import com.yun.baymax.R;
import com.yun.baymax.adapter.PictureSelectedAdapter;
import com.yun.baymax.bean.User;
import com.yun.baymax.bean.adapter.Feedback;
import com.yun.lib.utils.L;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UploadBatchListener;

public class FeedbackActivity extends BaseActivity implements TakePhoto.TakeResultListener, InvokeListener {

    private PictureSelectedAdapter adapter;
    private TakePhoto takePhoto;
    private InvokeParam invokeParam;
    private List<String> comPics = new ArrayList<>();
    private Map<String, String> pics = new HashMap<>();
    private EditText title;
    private EditText content;
    private Feedback feedback;

    @Override
    protected int setLayoutResourceId() {
        return R.layout.activity_public;
    }

    @Override
    protected void initVariables() {
        takePhoto = getTakePhoto();
    }

    @Override
    protected void initViews(Bundle savedInstanceState) {
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle(R.string.feedback);
        setSupportActionBar(toolbar);
        toolbar.setNavigationIcon(R.drawable.ic_arrow_back);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder dialog = new AlertDialog.Builder(FeedbackActivity.this);
                dialog.setMessage("内容将被丢弃，退出编辑？");
                dialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                dialog.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                        if (imm.isActive())
                            imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
                        finish();
                    }
                });
                dialog.show();
            }
        });

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (adapter.getDatas().size() > 20) {
                    Toast.makeText(FeedbackActivity.this, "最多添加20张图片", Toast.LENGTH_SHORT).show();
                    return;
                }
                showChooseDialog();
            }
        });

        title = (EditText) findViewById(R.id.title);
        content = (EditText) findViewById(R.id.content);
        content.setHint("内容(启奏陛下...)");

        RecyclerView mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);


        GridLayoutManager gridManager = new GridLayoutManager(mContext, 3);

        mRecyclerView.setLayoutManager(gridManager);

        adapter = new PictureSelectedAdapter(mContext);
        mRecyclerView.setAdapter(adapter);
    }

    @Override
    protected void loadData() {

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_publish, menu);
        return super.onCreateOptionsMenu(menu);

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        feedback = new Feedback();
        User currentUser = BmobUser.getCurrentUser(User.class);
        feedback.title = title.getText().toString();
        feedback.content = content.getText().toString();
        feedback.author = currentUser;
        if (adapter.getDatas().size() == 0)
            publish(feedback);
        else
            uploadImage();
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm.isActive())
            imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
        return super.onOptionsItemSelected(item);
    }

    public void showChooseDialog() {

        File file = new File(Environment.getExternalStorageDirectory(), "/temp/" + System.currentTimeMillis() + ".jpg");
        if (!file.getParentFile().exists()) file.getParentFile().mkdirs();
        final Uri imageUri = Uri.fromFile(file);

        String[] mStr = {"拍照", "手机相册"};
        AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
        dialog.setItems(mStr, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (which) {
                    case 0:
                        takePhoto.onPickFromCapture(imageUri);
                        break;
                    case 1:
                        takePhoto.onPickMultiple(6);
                        break;
                    default:
                        break;
                }
            }
        }).show();

    }

    /**
     * 获取TakePhoto实例
     *
     * @return
     */
    public TakePhoto getTakePhoto() {
        if (takePhoto == null) {
            takePhoto = (TakePhoto) TakePhotoInvocationHandler.of(this).bind(new TakePhotoImpl(this, this));
        }
        return takePhoto;
    }

    @Override
    public void takeSuccess(TResult tResult) {
        CompressConfig compressConfig = new CompressConfig.Builder().setMaxPixel(1080).create();
        compressImage(tResult.getImages(), compressConfig);
    }

    private void compressImage(ArrayList<TImage> tImage, CompressConfig compressConfig) {
        CompressImageImpl.of(mContext, compressConfig, tImage, new CompressImage.CompressListener() {

            @Override
            public void onCompressSuccess(ArrayList<TImage> images) {
                saveAndUp(images);
            }

            @Override
            public void onCompressFailed(ArrayList<TImage> images, String msg) {
                saveAndUp(images);
            }

            public void saveAndUp(ArrayList<TImage> images) {
                for (int i = 0; i < images.size(); i++) {
                    TImage tImage1 = images.get(i);
                    if (!comPics.contains(tImage1.getCompressPath()))
                        comPics.add(tImage1.getCompressPath());
                    Log.i("YUN", "compressPath:" + tImage1.getCompressPath());
                    pics.put(TextUtils.isEmpty(tImage1.getCompressPath()) ? tImage1.getOriginalPath() : tImage1.getCompressPath(), tImage1.getOriginalPath());
                }
                adapter.setDatas(comPics);
            }
        }).compress();
    }

    @Override
    public void takeFail(TResult tResult, String s) {

    }

    @Override
    public void takeCancel() {

    }

    @Override
    public PermissionManager.TPermissionType invoke(InvokeParam invokeParam) {
        PermissionManager.TPermissionType type = PermissionManager.checkPermission(TContextWrap.of(this), invokeParam.getMethod());
        if (PermissionManager.TPermissionType.WAIT.equals(type)) {
            this.invokeParam = invokeParam;
        }
        return type;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        getTakePhoto().onActivityResult(requestCode, resultCode, data);
    }

    private void uploadImage() {
        List<String> datas = adapter.getDatas();
        final int size = datas.size();
        String[] imgs = new String[size];
        for (int i = 0; i < size; i++) {
            imgs[i] = datas.get(i);
        }

        final ProgressDialog progressDialog = new ProgressDialog(mContext);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setTitle("正在发布...");
        progressDialog.show();

        BmobFile.uploadBatch(imgs, new UploadBatchListener() {
                    @Override
                    public void onSuccess(List<BmobFile> list, List<String> files) {
                        //bmobFile.getFileUrl()--返回的上传文件的完整地址
                        //1、files-上传完成后的BmobFile集合，是为了方便大家对其上传后的数据进行操作，例如你可以将该文件保存到表中
                        //2、urls-上传文件的完整url地址
                        if (list.size() == size) {
                            for (int i = 0; i < list.size(); i++) {
                                L.i(i + "" + list.get(i).getFileUrl());
                                L.i(i + "" + files.get(i));
                            }
                            feedback.pics = files;
                            publish(feedback);
                        }
                    }

                    @Override
                    public void onProgress(int i, int i1, int i2, int i3) {
                        //1、curIndex--表示当前第几个文件正在上传
                        //2、curPercent--表示当前上传文件的进度值（百分比）
                        //3、total--表示总的上传文件数
                        //4、totalPercent--表示总的上传进度（百分比）

                        progressDialog.setProgress(i3);
                        if (i2 == size && i3 == 100) {
                            //全部上传完成
                            progressDialog.dismiss();
                        }

                    }

                    @Override
                    public void onError(int i, String s) {
                        Toast.makeText(FeedbackActivity.this, s, Toast.LENGTH_SHORT).show();
                    }
                }

        );
    }

    private void publish(Feedback feedback) {
        feedback.save(new SaveListener<String>() {
            @Override
            public void done(String objectId, BmobException e) {
                if (e == null) {
                    Toast.makeText(mContext, "反馈成功", Toast.LENGTH_LONG).show();
                    finish();
                } else {
                    Toast.makeText(mContext, "反馈失败：" + e.getMessage(), Toast.LENGTH_LONG).show();
                }
            }
        });
    }

    @Override
    protected void onStop() {
        super.onStop();
    }
}
